package com.example.springcloud.rpc.client.config;

import com.example.springcloud.rpc.api.ErrorResult;
import com.example.springcloud.rpc.api.RpcException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import feign.Logger;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author fanhang
 */
@Configuration
public class FeignConfig {
    private final JsonMapper jsonMapper = JsonMapper.builder().build();

    @Bean
    public Logger.Level feignLogLevel() {
        return Logger.Level.BASIC;
    }

    @Bean
    public ErrorDecoder errorDecoder() {
        return new RpcErrorDecoder(jsonMapper);
    }


    public static class RpcErrorDecoder implements ErrorDecoder {
        private final JsonMapper jsonMapper;

        public RpcErrorDecoder(JsonMapper jsonMapper) {
            this.jsonMapper = jsonMapper;
        }

        @Override
        public Exception decode(String s, Response response) {
            try (InputStream in = response.body().asInputStream()) {
                ErrorResult errorResult = jsonMapper.readValue(in, ErrorResult.class);
                return new RpcException(errorResult.getCode(), errorResult.getMessage());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
